#/usr/bin/perl                                                                                                                           

# Input: .log file, .patterns file
# output: .grid  crypt_id, unique_clone_id, clone_id, day, generation
# output: .grid.pattern unique_clone_id,clone_id,ms_length_locus_1,..,ms_length_locus_n

# Get the grid at the end of simulation
my $day = 7300; 


# Read the log file and store unique clone ids
%cidhash;
for $sw ($ARGV[0]..$ARGV[1]){
    # Store ms pattern at each time step 
    %cidhash=();
    open (i1,"sweep$sw/sweep$sw.log");
    while(<i1>){
	chomp;
	@row=split(/\,/);
	if($row[2]==$day){
	    $cid = $row[1];
	    if(!defined($cidhash{$cid})){
		$cidhash{$cid}=1;
	    }
	}
    }
    close i1;    
}

%patterns;
for $sw ($ARGV[0]..$ARGV[1]){

    %patterns=();

    # Load all patterns in memory
    open (in,"sweep$sw/sweep$sw.patterns");
    while(<in>){
	chomp;
	@row=split(/\,/);
	# Skip loading cloneids from other timepoints
	if($cidhash{$row[0]}){
	    $patterns{$row[0]}="";
	    for my $loc (0..243){
		# Add to an array
		# Pattern is locus_id.ms_length.locus_id.ms_length
		# where length 100 is ignored
		if($row[$loc+1]!=100){
		    $patterns{$row[0]}=$patterns{$row[0]}.($loc+1).",".$row[$loc+1].","; 
		}
	    }
	}
    }
    close in;
    # Dead cells have cid=-1 so they have no pattern
    $patterns{-1}="";
    
    # Store ms pattern at each time step 
    %pathash=();
    $pat_count = 0;
    open (i1,"sweep$sw/sweep$sw.log");
    open (out, ">sweep$sw/sweep$sw.grid");
    open (out2, ">sweep$sw/sweep$sw.grid.patterns");
    while(<i1>){
	chomp;
	@row=split(/\,/);
	if($row[2]==$day){
	    
	    $pat = "";
	    $cid = $row[1];
	    # get the pattern from hash
	    # Here we assign a unique id for every unique pattern
	    # where two clones with different clone_ids can share the same pattern
	    # and therefore that pattern will have the same unique id.
	    $pat = $patterns{$cid};
	    if(!defined($pathash{$pat})){
		$pat_count++;
		$pathash{$pat}=$pat_count;
		# Output the pattern in .grid.patterns
		# pat_id, pattern
		my $pat_arr;
		for my $loc (0..243){
		    $pat_arr[$loc] = 100;
		}
		@arr = split(/\,/,$pat);
		# -2 instead of -1 because of trailing comma
		for my $loc (0..$#arr-2){
		    if($loc%2==0){
			$pat_arr[$arr[$loc]] = $arr[$loc+1];
		    }
		}
		# Print pattern id, cid, ...
		print out2 $pat_count.",".$cid.",";
		for my $loc (0..242){
		    print out2 $pat_arr[$loc].",";
		}
		print out2 $pat_arr[243]."\n";
	    }	    
	    print out $row[0].",".$pathash{$pat}.",".$cid.",".$row[2].",".$row[3]."\n";
	}
    }
    close i1;    
    close out;
    close out2;
}

    
